<template>
  <div class="app-container calendar-list-container">

    <el-form :inline="true" label-width="112px" :model="listQuery1" ref="listQuery1" :rules="rules" label-position="right" style="width: 100%">
        <el-form-item label="工序名称:" prop="processName" required>
            <el-input
                clearable
                v-model.trim="listQuery1.processName"
                style="width: 250px"
            ></el-input>
        </el-form-item>
        <el-form-item>
        <el-button
            type="danger"
            size="mini"
            round
            @click="cancelFormual"
            style="margin-left: 5px"
            v-if="isEdict">取消编辑</el-button>
        </el-form-item>
    </el-form>

    <el-form label-width="112px" style="margin: 10px 0 0 0">
        <el-form-item label="工资计算公式=">
            <div style="display: flex;flex-direction: row;align-item: center;">
            <el-input
                clearable
                v-model.trim="formual"
                :disabled="isValid"
                type="textarea"
                autosize
                style="width: 250px"
                readonly
            >
                <!-- <el-button slot="append" type="primary" @click="submitFormul">提交</el-button> -->
            </el-input>
            <div>
            <el-button size="mini" type="warning" icon="el-icon-delete" circle style="margin-left: 10px" v-if="!isValid" @click="deleteCharacter"></el-button>
            <el-button size="mini" type="danger" v-if="!isValid" @click="formual = ''">清空</el-button>
            <el-button size="mini" type="primary" v-if="isValid" @click="submitFormul" style="margin-left: 10px">提交</el-button>
            <template>
                <el-button
                    type="danger"
                    size="mini"
                    round
                    @click="formualValid"
                    style="margin-left: 5px"
                    v-if="!isValid">未校验</el-button>
                <el-button
                    type="success"
                    size="mini"
                    round
                    style="margin-left: 5px"
                    @click="isValid = false"
                    v-else>已校验</el-button>
            </template>
            <el-link :underline="false" type="danger">(格式例如：加工次数*难度系数*散单系数*单价)</el-link>
            </div>
            </div>
        </el-form-item>

        <el-form-item label="计算对象">
            <el-button :disabled="isValid" size="mini" @click="addparam(index)" style="margin-bottom: 5px" v-for="(item,index) in ableparamList" :key="index">{{item.name}}</el-button>
        </el-form-item>
        <el-form-item label="计算符号">
            <el-button :disabled="isValid" size="mini" @click="addsymbol(index)" style="margin-bottom: 5px" v-for="(item,index) in symbolList" :key="index">{{item}}</el-button>
        </el-form-item>
        <el-form-item label="数字键盘">
            <el-button :disabled="isValid" size="mini" @click="adddigit(index)" style="margin-bottom: 5px" v-for="(item,index) in digitList" :key="index">{{item}}</el-button>
        </el-form-item>

        <!-- <el-form-item>
            <el-select
                v-model="ableparam"
                filterable
                class="re-item"
                style="width: 120px;margin-left: 5px;"
                placeholder="可用变量名"
                >
                <el-option
                    v-for="(item,index) in ableparamList"
                    :key="index"
                    :label="item.name"
                    :value="item.name">
                </el-option>
            </el-select>
        </el-form-item> -->
    </el-form>

    <el-divider></el-divider>

    <div class="filter-container">
        <el-input
                @keyup.enter.native="handleFilter"
                clearable
                v-model="listQuery.processNameGz"
                style="width: 150px;margin-right:15px;margin-top:7px"
                class="filter-item"
                placeholder="工艺名称"
        ></el-input>

        <el-button style="margin-top:7px" class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

    <!-- 表单 -->
    <el-table :data="tableData"
    v-loading="tableLoading"
    element-loading-text="拼命加载中"
    stripe border fit
    highlight-current-row
    style="width: 100%">
        <el-table-column label="工序名称" prop="processNameGz" align="center"/>
        <el-table-column label="公式" prop="formula" align="center"/>
        <el-table-column label="长(mm)" prop="length" align="center"/>
        <el-table-column label="宽(mm)" prop="wide" align="center" width="70"/>
        <el-table-column label="厚(mm)" prop="thickness" align="center" width="70"/>
        <el-table-column label="重量" prop="weight" align="center"/>
        <el-table-column label="材质" prop="texture" align="center" width="100"/>
        <el-table-column label="加工次数" prop="processCount" align="center"/>
        <el-table-column label="操作"  align="center" width="120">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)"></el-button>
                <el-button
                    icon="el-icon-delete"
                    class="el-button el-button--danger"
                    style="font-size: 15px;"
                    @click="submitDel(scope.row,scope.$index)"
                ></el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>

    <!-- pagination 分页 -->
    <!-- <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40,100,300,500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div> -->

    <!-- 维护变量名是否启用数据弹窗 -->
    <el-dialog
      title="维护变量名是否启用"
      :visible.sync="showvar"
      @close="showvar = false"
      width="35%"
    >
        <el-form label-width="80px">
            <el-link :underline="false">工资计算方式包含以下变量名:</el-link>
            <!-- <el-form-item> -->
                <el-checkbox-group v-model="varList" style="margin-top: 20px">
                    <el-checkbox label="周长" @change="changeVarList"></el-checkbox>
                    <el-checkbox label="长"></el-checkbox>
                    <el-checkbox label="宽"></el-checkbox>
                    <el-checkbox label="厚"></el-checkbox>
                    <el-checkbox label="重量"></el-checkbox>
                    <el-checkbox label="材质"></el-checkbox>
                    <el-checkbox label="加工次数"></el-checkbox>
                </el-checkbox-group>
            <!-- </el-form-item> -->
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showvar = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addformual"
            :loading="createLoading"
            >确定</el-button
            >
        </div>
    </el-dialog>

  </div>
</template>

<script>
import { selFormulag,verifyEquation,saveFormulag,delFormulag,updFormulag } from "@/api/processRoute"
export default {
    name: 'addFormual',
    data() {
      return {
        tableLoading: false,
        listQuery: {},
        listQuery1: {},
        total: 0,
        tableData: [],
        formual: '',
        ableparamList: [
          {name:'单件重量',value:'DJZL'},
          {name:'单价',value:'DJ'},
          {name:'单价1',value:'DJ1'},
          {name:'单价2',value:'DJ2'},
          {name:'单价3',value:'DJ3'},
          {name:'难度系数',value:'NDXS'},
          {name:'散单系数',value:'SDXS'},
          {name:'定额人数',value:'DERS'},
          {name:'加工数量',value:'JGSL'},
          {name:'加工次数',value:'JGCS'},
          {name:'铆钉数量',value:'MDSL'},
          {name:'折弯刀数',value:'ZWDS'},
          {name:'单位平方',value:'DWPF'},
          {name:'连焊长度',value:'LHCD'},
          {name:'碰焊点数',value:'PHDS'},
          {name:'加工周长',value:'JGZC'},
          {name:'焊点数量',value:'HDSL'},
          {name:'扫码人数',value:'SCANLIMIT'},
          // 新增装配车间
          {name:'装配零件数量',value:'ZP_LJSL'},
          {name:'装配普通螺钉数量',value:'ZP_LDSL'},
          {name:'装配外购件数量',value:'ZP_WGJSL'},
          {name:'装配打胶长度',value:'ZP_DJCD'}, // DJ会被单价替换
          {name:'装配不锈钢螺钉数量',value:'ZP_BXGLDSL'},
          {name:'装配功率螺钉数量',value:'ZP_GLLDSL'},
          {name:'装配固定人时',value:'ZP_TIME'},
          // 新增喷涂车间  2月21号
          {name:'喷涂面积',value:'PBMJ'},
          {name:'保护面积',value:'BHMJ'},
          {name:'保护个数',value:'BHGS'},
           //   EMS装配  4月26号
          {name:'EMS装配计件',value:'EMS_ZPJJ'},
          {name:'EMS系数类型',value:'EMS_XXLS'},
          ]
          ,
        ableparam: '',
        isValid: false,
        showvar: false,
        varList: [],
        createLoading: false,
        fieldListBlean: {
            length: false,
            wide: false,
            thickness: false,
            weight: false,
            texture: false,
            processCount: false
        },
        rules: {
            processName: [
                { required: true, message: "工序名称不能为空", trigger: "change" },
            ],
        },
        fieldList: [{name:'长',value:'length'},{name:'宽',value:'wide'},{name:'厚',value:'thickness'},{name:'重量',value:'weight'},{name:'材质',value:'texture'},{name:'加工次数',value:'processCount'}],
        isEdict: false,
        symbolList: ['+','-','*','/','(',')'],
        digitList: ['1','2','3','4','5','6','7','8','9','0','.']
      };
    },
    methods: {
        async handleFilter() {
            this.tableData = []
            // if(!this.listQuery.processName) return this.$message.error('工艺名称不能为空!')
            this.tableLoading = true
            let query = Object.assign({},this.listQuery)
            // if(!query.type) delete query.type
            const data = await selFormulag(query)
            this.tableLoading = false
            this.tableData = data.data
            if(!this.tableData.length) return
            this.tableData.forEach((item,index) => {
                item.formula = this.getValue(item.formula)
            })
        },
        getValue(key){
            let name = key
            this.ableparamList.forEach((item,index) => {
             if(name.includes('DJZL')){
                let reg = new RegExp('DJZL','g')
                name = name.replace(reg,'单价重量')
              }else if(name.includes('ZP_DJCD')){
                let reg = new RegExp('ZP_DJCD','g')
                name = name.replace(reg,'装配打胶长度')
              }else if(name.includes('DJ')){
                let reg = new RegExp('DJ','g')
                name = name.replace(reg,'单价')
              }else if(name.includes(item.value)){
                let reg = new RegExp(item.value,'g')
                name = name.replace(reg,item.name)
                }
            })
            return name
        },
        handleSizeChange(val) {
            this.listQuery.limit = val
            this.handleFilter()
        },
        handleCurrentChange(val) {
            this.listQuery.page = val
            this.handleFilter()
        },
        toAddprocessCategory() {
            this.$router.push({
                path: 'addprocessCategory',
                name: 'addprocessCategory',
                params: {data: ''}
            })
        },
        handleEdit(row){
            this.varList = []
            // this.listQuery1.processName = row.processNameGz
            this.$set(this.listQuery1, 'processName', row.processNameGz)
            this.formual = row.formula
            // this.$set(this.listQuery1, 'formula', row.formula)
            this.isValid = true
            this.isEdict = true
            if(row.length == 'true') { this.varList.push(this.getValueVarName('length')) }
            if(row.wide == 'true') { this.varList.push(this.getValueVarName('wide')) }
            if(row.thickness == 'true') { this.varList.push(this.getValueVarName('thickness')) }
            if(row.weight == 'true') { this.varList.push(this.getValueVarName('weight')) }
            if(row.texture == 'true') { this.varList.push(this.getValueVarName('texture')) }
            if(row.processCount == 'true') { this.varList.push(this.getValueVarName('processCount')) }
        },
        cancelFormual(){
            this.isEdict = false
            this.formual = ''
            this.listQuery1.processName = ''
            this.isValid = false
            this.varList = []
        },
        getValueVarName(key){
            let value = ''
            this.fieldList.forEach((item,index) => {
                if(item.value == key){
                    value = item.name
                }
            })
            return value
        },
        submitDel(row,index) {
            this.$confirm('是否确认删除', '注意', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.deleteData(row,index)
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消'
                });
              });
        },
        async deleteData(row,index){
            const data = await delFormulag({processNameGz: row.processNameGz})
            if(data.code == '500') return
            if(data.code == '2') return this.$message.error(data.msg)
            if(data.code == '1'){
                  this.tableData.splice(index,1)
                  this.$message({
                    message:data.msg,
                    type:'success'
                 })
            }
        },
        changeVarList(e){
            if(e){
                this.varList.push('长')
                this.varList.push('宽')
            }
        },
        async formualValid(){
            if(!this.formual) return this.$message.error('公式不能为空')
            let formual = this.formual
            // console.log('formual',formual);
            let obj = {}
            this.ableparamList.forEach((item,index) => {
              if(formual.includes('单价1')){
                let reg = new RegExp('单价1','g')
                    formual = formual.replace(reg,'DJ1')
                    obj['DJ1'] = index
              }else if(formual.includes('单价2')){
                let reg = new RegExp('单价2','g')
                    formual = formual.replace(reg,'DJ2')
                    obj['DJ2'] = index
              }else if(formual.includes('单价3')){
                let reg = new RegExp('单价3','g')
                    formual = formual.replace(reg,'DJ3')
                    obj['DJ3'] = index
              }else if(formual.includes('单价')){
                let reg = new RegExp('单价','g')
                    formual = formual.replace(reg,'DJ')
                    obj['DJ'] = index
              }else if(formual.includes('单件重量')){
                let reg = new RegExp('单件重量','g')
                    formual = formual.replace(reg,'DJZL')
                    obj['DJZL'] = index
              }else  if(formual.includes(item.name)){
                    let reg = new RegExp(item.name,'g')
                    formual = formual.replace(reg,item.value)
                    // formual = formual.replace(item.name,item.value)
                    obj[item.value] = index
                }
            })
            obj.eval = formual
            var pattern = new RegExp("[\u4E00-\u9FA5]+")
            if(pattern.test(formual)) return this.$message.error('公式存在不知名变量名，请检查公式是否正确!')
            delete obj.type
            let data = await verifyEquation(obj)
            if(data.code == '500'){
                this.$message.error('检查公式是否正确!')
                return
            }
            if(data.code == '1'){
                this.isValid = true
            } else {
                this.$message.error(data.msg)
            }
        },
        submitFormul(){
            this.$refs['listQuery1'].validate((valid) => {
                if (valid) {
                    if(!this.isValid) return this.$message.error('请先校验工资计算方式!')
                    this.showvar = true
                } else {

                }
            })
        },
        async addformual(){
            // if(!this.varList.length) return this.$message.error('至少选择一个变量名!')
            this.createLoading = true
            setTimeout(() => {
                this.createLoading = false
            }, 2000);
            let obj = Object.assign({},this.fieldListBlean)
            obj.processNameGz = this.listQuery1.processName
            this.varList.forEach((item,index) => {
                if(item != '周长'){ obj[this.getValueVar(item)] = true }
            })
            let formual = this.formual
            this.ableparamList.forEach((item,index) => {
                if(formual.includes(item.name)){
                    let reg = new RegExp(item.name,'g')
                    formual = formual.replace(reg,item.value)
                    // formual = formual.replace(item.name,item.value)
                }
            })
            obj.formula = formual
            let data = this.isEdict?await updFormulag(obj):await saveFormulag(obj)
            if(data.code == '500') return
            const errMsg = data.msg
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.showvar = false
            this.handleFilter()
            this.cancelFormual()
        },
        getValueVar(key){
            let value = ''
            this.fieldList.forEach((item,index) => {
                if(item.name == key){
                    value = item.value
                }
            })
            return value
        },
        addparam(index){
            this.formual = this.formual + this.ableparamList[index].name
        },
        addsymbol(index){
            this.formual = this.formual + this.symbolList[index]
        },
        adddigit(index){
            this.formual = this.formual + this.digitList[index]
        },
        deleteCharacter(){
            this.formual = this.formual.substring(0,this.formual.length-1)
        }
    },
      // 在生命周期函数调用"搜索"按钮绑定的函数，显示已有的数据
    mounted() {
        this.handleFilter()
    },
};
</script>

<style>

</style>
